import {Component, OnInit} from '@angular/core';
import {DatePipe} from '@angular/common';

@Component({
    selector: 'app-demo-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.scss'],
})
export class ListComponent implements OnInit {
    loading: string;
    list: string[];
    page: number;

    constructor(
        private date: DatePipe
    ) {
        this.loading = 'loading';
        this.list = [];
        this.page = 1;
    }

    ngOnInit() {
        this.loading = 'loading';
        setTimeout(() => {
            this.list = this.getList();
            this.loading = '';
        }, 2000);
    }

    getList() {
        let dataSource = 20;
        if (this.page >= 3) {
            dataSource = 10;
        }
        const result: string[] = [];
        const item = Date.now();
        for (let i = 0; i < dataSource; i++) {
            result.push(`时间为: ${this.date.transform(item, 'yyyy-MM-dd HH:mm:ss')}, 第${i}条数据`);
        }
        return result;
    }

    getDrop() {
        setTimeout(() => {
            this.list = this.getList();
            this.page = 1;
            this.loading = 'drop';
        }, 2000);
    }

    dataUpdate(val: string) {
        const value = this.list;
        switch (val) {
            // 下拉刷新
            case 'pull':
                this.page += 1;
                setTimeout(() => {
                    const data = this.getList();
                    // 每页20条数据
                    if (data.length >= 20) {
                        this.loading = 'pull';
                    } else {
                        this.page -= 1;
                        this.loading = 'noMore';
                    }
                    this.list = value.concat(data);
                }, 2000);
                break;
            // 上拉加载
            case 'drop':
                this.getDrop();
                break;
        }
    }

    clear() {
        this.loading = '';
    }
}
